package com.cz.nongyetongv5.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.activity.EntDetailActivity;
import com.cz.nongyetongv5.activity.SuperviseListActivity;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.EntDetailBean;
import com.cz.nongyetongv5.bean.JsonUtil;
import com.cz.nongyetongv5.bean.SuperviseList;
import com.cz.nongyetongv5.bean.SuperviseListBean;
import com.cz.nongyetongv5.bean.SuperviseListResponse;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


/**
 * 文件：ams.java
 * 包名：com.ronri.ams.task;
 * 说明：
 * 作者：MS During
 * 日期：2017/5/18
 * 历史：
 */
public class SuperviseListFragment extends Fragment {

    private View view;
    RecyclerView recyclerView;
    SmartRefreshLayout refreshLayout;
    private int page = 1;
    private int size = 10;
    private SuperviseListAdapter adapter;
    private List<SuperviseList> superviseLists;
    private boolean isShowEdit = false;
    private int position = 1;
    private String status;


    private String add_user;
    //    private String regions;
    private String region_code;
    private SuperviseListResponse superviseListResponse;
    private SuperviseListBean superviseListBean;
    private int indexTag;

    public static SuperviseListFragment newInstance(int position, String add_user, String status, String region_code) {
        SuperviseListFragment fragment = new SuperviseListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putString("add_user", add_user);
        //        bundle.putString("regions", regions);
        bundle.putString("status", status);
        bundle.putString("region_code", region_code);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_ent_list, null);
        position = getArguments().getInt("position");
        add_user = getArguments().getString("add_user");
        //        regions = getArguments().getString("regions");
        status = getArguments().getString("status");
        region_code = getArguments().getString("region_code");
        recyclerView = view.findViewById(R.id.recyclerView);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        superviseLists = new ArrayList<>();
        adapter = new SuperviseListAdapter();
        View notDataView = getActivity().getLayoutInflater().inflate(R.layout.view_nodata, (ViewGroup) recyclerView.getParent(), false);
        adapter.setEmptyView(notDataView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter); //设置分页和下拉刷新
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        //设置 Footer
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getSuperviseList();
                //                WaitDialog.ShowDialog(getActivity(),"数据加载中...");

            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (superviseListBean != null) {
                    if (page < superviseListBean.getTotal()) {
                        page++;
                        getSuperviseList();
                    } else {
                        refreshLayout.finishLoadmore();
                        Toast.makeText(getActivity(), "没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    refreshLayout.finishLoadmore();
                    Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
                }


            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                indexTag = position;
                getSuperviseDetail(superviseLists.get(position).getEnt_id());
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (superviseLists.get(position).isChecked()) {
                    superviseLists.get(position).setChecked(false);
                } else {
                    superviseLists.get(position).setChecked(true);
                }
                adapter.notifyDataSetChanged();
                int sum = 0;
                for (SuperviseList superviseList : superviseLists) {
                    if (superviseList.isChecked()) {
                        sum++;
                    }
                }
                if (sum == superviseLists.size()) {
                    TextView tv = (TextView) getActivity().findViewById(R.id.tv_right);
                    tv.setText("全不选");
                    if (position == 1) {
                        ((SuperviseListActivity) getActivity()).setAddIndex(3);
                    } else if (position == 2) {
                        ((SuperviseListActivity) getActivity()).setCancelIndex(3);
                    }
                } else {
                    TextView tv = (TextView) getActivity().findViewById(R.id.tv_right);
                    tv.setText("全选");
                    if (position == 1) {
                        ((SuperviseListActivity) getActivity()).setAddIndex(2);
                    } else if (position == 2) {
                        ((SuperviseListActivity) getActivity()).setCancelIndex(2);
                    }
                }
            }
        });
        //        WaitDialog.ShowDialog(getActivity(),"数据加载中...");
        getSuperviseList();
        return view;
    }


    public class SuperviseListAdapter extends BaseQuickAdapter<SuperviseList, BaseViewHolder> {
        public SuperviseListAdapter() {
            super(R.layout.supervise_list_item, superviseLists);
        }

        @Override
        protected void convert(BaseViewHolder helper, SuperviseList item) {
            if (item.getEnt_name() != null) {
                helper.setText(R.id.tv_ent_name, item.getEnt_name() + "（" + item.getTrade_name() + ")");
            }
            if (item.getRealname() != null) {
                helper.setText(R.id.tv_admin, item.getRealname() + "(" + item.getRegion_name() + ")");
            }
            if (item.getAdd_time() != null) {
                helper.setText(R.id.tv_date, item.getAdd_time());
            }
            if (isShowEdit) {
                helper.setVisible(R.id.cb_choose, true);
            } else {
                helper.setVisible(R.id.cb_choose, false);
            }
            helper.addOnClickListener(R.id.cb_choose);
            helper.setChecked(R.id.cb_choose, item.isChecked());
        }
    }

    public void closeRefresh() {
        if (refreshLayout != null) {
            if (refreshLayout.isRefreshing()) {
                refreshLayout.finishRefresh();
            } else if (refreshLayout.isLoading()) {
                refreshLayout.finishLoadmore();
            }
        }
    }


    public void setNotify(boolean isShowEdit) {
        this.isShowEdit = isShowEdit;
        adapter.notifyDataSetChanged();
    }

    public int getSize() {
        return superviseLists.size();
    }

    public void setSelect(boolean isSelect) {
        for (SuperviseList superviseList : superviseLists) {
            superviseList.setChecked(isSelect);
        }
        adapter.notifyDataSetChanged();
    }


    /**
     * 获取选中的item
     *
     * @return
     */
    public List<SuperviseList> getSelected() {
        List<SuperviseList> selectedItems = new ArrayList<>();
        for (SuperviseList superviseList : superviseLists) {
            if (superviseList.isChecked()) {
                selectedItems.add(superviseList);
            }
        }
        return selectedItems;
    }

    public void setUpdatet(boolean isShowEdit) {
        this.isShowEdit = isShowEdit;
        page = 1;
        getSuperviseList();
    }

    void getSuperviseDetail(String id) {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "ent/entDetail.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("id", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getActivity(), "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //                        System.out.println(response);

                        Gson gson = new Gson();
                        EntDetailBean entDetailBean = gson.fromJson(response, EntDetailBean.class);
                        //                        EntDetailBean entDetailBean = JsonUtil.toObject(response, EntDetailBean.class);
                        if (entDetailBean.getCode() == 0) {
                            if (entDetailBean.getData() != null) {
                                Intent intent = new Intent(getActivity(), EntDetailActivity.class);
                                intent.putExtra("type", 3);
                                intent.putExtra("supervise_id", superviseLists.get(indexTag).getSupervise_id());
                                intent.putExtra("status", superviseLists.get(indexTag).getStatus());
                                intent.putExtra("entBean", entDetailBean.getData());
                                intent.putExtra("add_user", add_user);
                                intent.putExtra("region_code", region_code);
                                startActivity(intent);
                            } else {
                                Toast.makeText(getActivity(), "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(getActivity(), "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    void getSuperviseList() {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "supervise/checkSuperviseList.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(size))
                .addParams("region_code", region_code)
                .addParams("add_user", add_user)
                .addParams("status", status)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getActivity(), "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        closeRefresh();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response);
                        closeRefresh();
                        superviseListResponse = JsonUtil.toObject(response, SuperviseListResponse.class);
                        if (superviseListResponse.getCode() == 0) {
                            superviseListBean = superviseListResponse.getData();
                            if (page == 1) {
                                superviseLists.clear();
                                superviseLists.addAll(superviseListBean.getRows());
                            } else {
                                superviseLists.addAll(superviseListBean.getRows());
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(getActivity(), "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        getSuperviseList();
    }

}
